/**
 *
 *@author ZhouLan
 *@version 1.1.0
 */

import fs from '@ohos.file.fs';
import common from '@ohos.app.ability.common';
import {fileName} from '../configs/Config'
import {ListFormat} from '../entity/Communications'
import ArrayList from '@ohos.util.ArrayList';

export class FileUtil{
  private static  getFile(context:common.UIAbilityContext){
    let fileDir = context.filesDir
    console.log("dir:"+fileDir)
    let file = fs.openSync(fileDir+'/'+fileName,fs.OpenMode.READ_WRITE|fs.OpenMode.CREATE)
    return file
  }
  static setMessageToFile (context:common.UIAbilityContext,json:string|object){
    let file = this.getFile(context)
    if(typeof json == "object"){
      json = JSON.stringify(json)
    }
    let num = fs.writeSync(file.fd,json)
    fs.close(file)
    //关闭文件流
    return num
  }
  static getMessageFromFile(context:common.UIAbilityContext) : Array<ListFormat>{
    this.initFile(context)
    let fileDir = context.filesDir
    console.log("dir"+fileDir)
    //空的json字符串，出现报错
    return JSON.parse(fs.readTextSync(fileDir+'/'+fileName))
  }
  static initFile(context:common.UIAbilityContext){
    let filePath = context.filesDir+"/"+fileName
    let file = fs.openSync(filePath,fs.OpenMode.READ_WRITE|fs.OpenMode.CREATE)
    let str = fs.readTextSync(filePath)
    if(str.length==0){
      fs.writeSync(file.fd,"{}")
    }
  }
}